import { PanelItemController } from '@ibiz-template/runtime';
import { OdooChatState } from './odoo-chat.state';
import { IChatItem } from '../interface';

/**
 * @description odoo聊天控制器
 * @export
 * @class OdooChatController
 * @extends {PanelItemController}
 */
export class OdooChatController extends PanelItemController {
  /**
   * @description 状态对象
   * @type {OdooChatState}
   * @memberof OdooChatController
   */
  declare state: OdooChatState;

  /**
   * @description 创建状态对象
   * @protected
   * @returns {*}  {OdooChatState}
   * @memberof OdooChatController
   */
  protected createState(): OdooChatState {
    return new OdooChatState(this.parent?.state);
  }

  /**
   * @description 初始化
   * @protected
   * @returns {*}  {Promise<void>}
   * @memberof OdooChatController
   */
  protected async onInit(): Promise<void> {
    await super.onInit();
    this.addChat = this.addChat.bind(this);
    ibiz.odooChatUtil?.onAdd(this.addChat);
    const chats = window.localStorage.getItem('OdooChat');
    if (chats) this.state.chatList = JSON.parse(chats);
  }

  /**
   * @description 清空聊天
   * @memberof OdooChatController
   */
  clearChat(): void {
    this.state.chatList = [];
    this.saveChat();
  }

  /**
   * @description 删除聊天
   * @param {string} key
   * @memberof OdooChatController
   */
  removeChat(key: string): void {
    const index = this.state.chatList.findIndex(c => c.key === key);
    if (index !== -1) {
      this.state.chatList.splice(index, 1);
      this.saveChat();
    }
  }

  /**
   * @description 添加聊天
   * @param {IChatItem} chat
   * @memberof OdooChatController
   */
  addChat(chat: IChatItem): void {
    const index = this.state.chatList.findIndex(c => c.key === chat.key);
    if (index > -1) {
      this.onChartOpenChage(chat.key);
    } else {
      this.state.chatList.unshift(chat);
      this.saveChat();
    }
  }

  /**
   * @description 聊天打开状态变更
   * @param {string} key
   * @memberof OdooChatController
   */
  onChartOpenChage(key: string): void {
    const index = this.state.chatList.findIndex(c => c.key === key);
    if (index > -1) {
      // 移除找到的元素
      const [movedItem] = this.state.chatList.splice(index, 1);
      movedItem.isOpen = !movedItem.isOpen;
      // 将元素添加到数组开头
      this.state.chatList.unshift(movedItem);
      this.saveChat();
    }
  }

  /**
   * @description 保存聊天
   * @private
   * @memberof OdooChatController
   */
  private saveChat(): void {
    window.localStorage.setItem(
      'OdooChat',
      JSON.stringify(this.state.chatList),
    );
  }

  /**
   * @description 销毁
   * @memberof OdooChatController
   */
  destroy(): void {
    super.destroy();
    ibiz.odooChatUtil?.offAdd(this.addChat);
  }
}
